import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Resource } from '@modelcontextprotocol/sdk/types';
import { Logger } from '~/utils/logger';

export interface SwaggerResource extends Resource {
  uri: string;

  name: string;

  description: string;

  mimeType: string;

  /** blob 的 Base64 编码 */
  blob?: string;

  text?: string; // 可选的文本内容
}

export const transientSwaggerResourceStore = new Map<string, SwaggerResource>(); // Key: resource.uri

export const swaggerResourceUriPrefix = 'swagger://'; // Prefix for transient resources

export const swaggerResourceTemplate = new ResourceTemplate(
  `${swaggerResourceUriPrefix}{host}-{path}`,
  {
    list: function () {
      const keys = transientSwaggerResourceStore.keys();

      const resources = Array.from(keys)
        .map(key => {
          const resource = transientSwaggerResourceStore.get(key);
          if (resource) {
            return {
              uri: resource.uri,
              mimeType: resource.mimeType,
              name: resource.name,
              description: resource.description,
            };
          }
          return null;
        })
        .filter(Boolean) as Array<{
        uri: string;
        mimeType: string;
        name?: string;
        description?: string;
      }>;

      Logger.info(`[SwaggerResourceTemplate] 返回 ${resources.length} 个资源`);

      return {
        resources,
      };
    },
  }
);

export function getSwaggerResourceByUri(uri: string): SwaggerResource | null {
  return transientSwaggerResourceStore.get(uri) || null;
}
